package com.android.qos;

import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class SimuHtmlReq {
    private static final String LOG_TAG = "simu";
    private String testUrl ="";
    private String result = "";
    public SimuHtmlReq(String myUrl) {
        testUrl = myUrl+"/regist/registcommit/";
    }
    
    public String getResult() {
        return result;
    }
    
    public void encapTest() {
        Log.d("Simu", "encap test");
        new Thread(new Runnable() {
            public void run() {
                try {
                    testConn();
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
            }
        }).start();
    }
    
    public void testConn() throws JSONException, ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //ResponseHandler <String> resonseHandler = new BasicResponseHandler();
        HttpPost postMethod = new HttpPost(testUrl);
        Log.d(LOG_TAG, "test url is: "+testUrl);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);

        nameValuePairs.add(new BasicNameValuePair("username", "test"));
        nameValuePairs.add(new BasicNameValuePair("password", "1234"));
        nameValuePairs.add(new BasicNameValuePair("email", "789"));
        
        postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpClient.execute(postMethod/*,resonseHandler*/);
        
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = reader.readLine();
        
        JSONTokener tokener = new JSONTokener(line);
        JSONObject jsb = new JSONObject(tokener);
        Log.d(LOG_TAG, "response is : "+jsb.getString("result"));
        
        //set result
        result = jsb.getString("result");
   }
}